<?php
/**
 * Wysiwym.php
 *
 * @category    Madoqua
 * @package     View
 * @subpackage  Helper
 */

/** base class */
require_once 'Madoqua/View/Helper/Abstract.php';

/**
 * Madoqua_View_Helper_Wysiwym
 *
 * helper to generate the correct js for wysiwym editing
 *
 * @category    Madoqua
 * @package     View
 * @subpackage  Helper
 */
class Madoqua_View_Helper_Wysiwym extends Madoqua_View_Helper_Abstract
{
    /**
     * counter
     *
     * @var int
     */
    protected $_counter = 0;
    
    /**
     * add js to the head for Wysiwym usage,
     * by default it will convert all textareas with class="richtext"
     *
     * @param string $id id of the element to add the editor to
     * @param Madoqua_Form $form the form you want to be edited
     */
    public function wysiwym($id, $form)
    {
        $this->headScript()->appendFile($this->adminFile('js/library/wymeditor/jquery.wymeditor.pack.js'));
        //main js include

        $oldClass = split(' ', $form->getAttrib('class'));
        //old class names for the form
        
        $exist = preg_grep('$_wysiwym_$', $oldClass);
        //try to figure out whether form already has wysiwym
        
        if (count($exist) == 0) {
            //form hasn't had wysiwym added to it yet (yay! we get to add it!)
            
            $className = '_wysiwym_' . $this->_counter++;
            //the form class name were working with
            
            $formClass = $form->getAttrib('class') . ' ' . $className;
            $form->setAttrib('class', $formClass);
            //add classname to it        
        } else {
            //I has a wysiwym \ó/
            $className = array_pop($exist);
        }
        
        $id = 'form.' . $className . ' #' . trim($id);
        //id must be part of the form

        $js = 'jQuery(function() {
            var element =  $("' . $id . '");
            
            var html = $("' . $id . '").value;
            
            jQuery("' . $id . '").wymeditor({
                html: html,
                updateSelector: "form.' . $className . '",
                updateEvent: "submit",
                skin: "madoqua",
                classesHtml: "",
                postInit: function(wym) {
                }
                        
            });
        });';
        //js to be added, will turn on the editor for the selected element
        //form submit is tracked (to trigger the update of the textarea)
        
        $this->headScript()->appendScript($js);
        //append it (durrrr)
    }
}